package com.example.PDFdemo.pdffinalplan;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PDFUtil {
    public static void addText(String oldFilePath, String newFilePath, List<PDFModel> models) throws DocumentException, IOException {
        PdfReader reader = new PdfReader(oldFilePath);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(newFilePath));

        for (PDFModel model : models) {
            if (model.getImgUrl() == null) {
                //设置基础字体
                String fontPath = "static/" + model.getFontName() + ".ttf";
                //颜色16进制转RGB
                Map<String, Integer> RGB = PDFUtil.hex2RGB(model.getColor());
                BaseFont baseFont = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                BaseColor color = new BaseColor(RGB.get("red"), RGB.get("green"), RGB.get("bule"));
                Font font = new Font(baseFont, model.getFontSize());
                //字体颜色
                font.setColor(color);
                //设置字体样式   加粗 0不加粗，1加粗，默认不加粗   倾斜 0不倾斜，2倾斜，默认不倾斜
                font.setStyle(model.getFontBold() + model.getFontIncline());
                //添加文本
                PdfContentByte over = stamper.getOverContent(model.getPageNumber());
                ColumnText columnText = new ColumnText(over);
                //不能实现文字在垂直方向的位置设置
                columnText.setSimpleColumn(model.getW(), model.getH(), model.getX(), model.getY(), model.getLeading(), model.getHorizontal());
                Phrase phrase = new Phrase(model.getContent(), font);
                columnText.addText(phrase);
                columnText.go();
                //使用表格+单元格的实行能够实现文字在垂直方向的位置设置
       /*         Rectangle rect = new Rectangle(model.getLlx(), model.getLly(), model.getUrx(), model.getUry());
                Paragraph paragraph =new Paragraph(model.getContent(), font);
                PdfPTable table = new PdfPTable(1);
                table.setHorizontalAlignment(Element.ALIGN_LEFT);
                table.setTotalWidth(rect.getWidth());
                //System.out.println("矩形1宽：" + rect.getWidth() + "  矩形1长：" + rect.getHeight() + "  表格宽：" + table.getTotalWidth() + "  表格高：" + table.getTotalHeight());
                PdfPCell cell = new PdfPCell(paragraph);
                cell.setFixedHeight(rect.getHeight());
                //System.out.println("单元格高度：" + cell.getFixedHeight() + "   单元格高度：" + cell.getWidth());
                cell.setHorizontalAlignment(model.getHorizontal());
                cell.setVerticalAlignment(model.getVertical());
                //cell.setBackgroundColor(BaseColor.GRAY);
                //消除表格边框
                cell.disableBorderSide(15);
                table.addCell(cell);
                columnText.setSimpleColumn(rect);
                columnText.addElement(table);
                columnText.go();*/
            } else {
                //创建矩形
                Rectangle rect = new Rectangle(model.getW(), model.getH(), model.getX(), model.getY());
                //System.out.println("矩形2宽：" + rect.getWidth() + "  矩形2长：" + rect.getHeight());
                //获取图片
                Image image = Image.getInstance(model.getImgUrl());
                //设置图片的大小，铺满整个ColumnText
                //image.scalePercent(100f);
                //image.scaleToFit(Math.max(model.getLlx(), model.getUrx())-Math.min(model.getLlx(), model.getUrx()), Math.max(model.getLly(), model.getUry()));
                image.scaleToFit(rect);
                image.setAlignment(Element.ALIGN_CENTER);
                //image.scaleAbsoluteHeight(rect.getHeight());
                //image.scaleAbsoluteWidth(rect.getWidth());
                //System.out.println("图宽：" + image.getWidth() + "   图长：" + image.getHeight() +  "   百分比宽度：" + image.getWidthPercentage());
                //添加图片
                PdfContentByte over = stamper.getOverContent(model.getPageNumber());
                ColumnText columnText = new ColumnText(over);
                //columnText.setSimpleColumn(model.getLlx(), model.getLly(), model.getUrx(), model.getUry());
                columnText.setSimpleColumn(rect);
                columnText.addElement(image);
                columnText.go();
            }
        }
        stamper.close();
        reader.close();
    }

    public static void addText2(String oldFilePath, String newFilePath, List<PDFModel> models) throws DocumentException, IOException {
        PdfReader reader = new PdfReader(oldFilePath);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(newFilePath));

        for (PDFModel model : models) {
            if (model.getImgUrl() == null) {
                //设置基础字体
                String fontPath = "static/" + model.getFontName() + ".ttf";
                //颜色16进制转RGB
                Map<String, Integer> RGB = PDFUtil.hex2RGB(model.getColor());
                BaseFont baseFont = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                BaseColor color = new BaseColor(RGB.get("red"), RGB.get("green"), RGB.get("blue"));
                Font font = new Font(baseFont, model.getFontSize());
                //字体颜色
                font.setColor(color);
                //设置字体样式   加粗 0不加粗，1加粗，默认不加粗   倾斜 0不倾斜，2倾斜，默认不倾斜
                font.setStyle(model.getFontBold() + model.getFontIncline());
                //添加文本
                PdfContentByte over = stamper.getOverContent(model.getPageNumber());
                ColumnText columnText = new ColumnText(over);
                //使用表格+单元格的实行能够实现文字在垂直方向的位置设置
                Rectangle pageRect = new Rectangle(reader.getPageSizeWithRotation(model.getPageNumber()));
                float x = pageRect.getRight();
                float y = pageRect.getTop();
                Rectangle textRect = new Rectangle(model.getX() * x, model.getY() * y, model.getX() * x + model.getW() * x, model.getY() * y + model.getH() * y);
                //Rectangle textRect = new Rectangle(model.getX() * x, model.getY() * y, x * model.getW(), y * model.getH());
                Paragraph paragraph =new Paragraph(model.getContent(), font);
                PdfPTable table = new PdfPTable(1);
                //table.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.setTotalWidth(textRect.getWidth());
                //设置单元格在表格中的宽度占比，默认为80%
                table.setWidthPercentage(100);
                table.setSplitLate(false);
                PdfPCell cell = new PdfPCell(paragraph);
                cell.setFixedHeight(textRect.getHeight());
                cell.setHorizontalAlignment(model.getHorizontal());
                cell.setVerticalAlignment(model.getVertical());
                //段落的行间距
                //cell.setLeading(model.getLeading(), 0);
                //消除表格边框
                cell.disableBorderSide(15);
                table.addCell(cell);
                columnText.setSimpleColumn(textRect);
                //System.out.println(columnText.getFilledWidth() + " " + columnText.getYLine());
                //columnText.setLeading(model.getLeading());
                columnText.addElement(table);
                columnText.go();
            } else {
                PdfContentByte over = stamper.getOverContent(model.getPageNumber());
                //创建矩形
                Rectangle rect = new Rectangle(reader.getPageSizeWithRotation(model.getPageNumber()));
                float x = rect.getRight();
                float y = rect.getTop();
                //获取图片
                Image image = Image.getInstance(model.getImgUrl());
                //添加图片
                over.saveState();
                PdfGState state = new PdfGState();
                // 设置填充透明度
                state.setFillOpacity(1.0f);
                over.setGState(state);
                // pdf 图层图片渲染
                over.addImage(image, x * model.getW(), 0f, 0f, y * model.getH(), model.getX() * x, model.getY() * y);
                //over.addImage(image, model.getX() * x, 0, 0, model.getY() * y,x * model.getW(), y * model.getH(), true)
                over.restoreState();
            }
        }
        stamper.close();
        reader.close();
    }

    //十六进制转RGB
    public static Map<String, Integer> hex2RGB(String hexStr){
        if(hexStr != null && !"".equals(hexStr) && hexStr.length() == 7){
            Map<String, Integer> rgb = new HashMap();
            rgb.put("red", Integer.valueOf(hexStr.substring( 1, 3 ), 16));
            rgb.put("green", Integer.valueOf(hexStr.substring( 3, 5 ), 16));
            rgb.put("blue", Integer.valueOf(hexStr.substring( 5, 7 ), 16));
            return rgb;
        }
        return null;
    }


}
